<template>
  <div>
    <!-- 头部 -->
    <el-card class="head-content">
      <div class="head-content-box">
        <span class="head-content-txt">标签管理</span>
        <div style="width: 1px;height: 50px;background-color: #797979; margin-left: 20px;" />
        <div class="head-content-txt-newlyAdded" @click="NewLabel">
          <i class="el-icon-circle-plus-outline head-content-txt-newlyAdded-icon" />
          <span class="head-content-txt-newlyAdded-txt">新增标签</span>
        </div>
      </div>
    </el-card>
    <!-- 表格 -->
    <el-card class="form-content">
      <el-form ref="form" :model="form" :inline="true" size="small">
        <el-form-item>
          <el-input v-model="form.labelName" placeholder="请输入标签名称关键字" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="启用" value="Y" />
            <el-option label="禁用" value="N" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchData('init')">搜索</el-button>
          <el-button type="primary" @click="empty">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" border style="width: 100%" row-key="id">
        <el-table-column prop="labelName" align="center">
          <template slot-scope="scope">
            <i class="move el-icon-s-operation" />
          </template>
        </el-table-column>
        <el-table-column prop="labelName" label="标签名称" align="center" />
        <el-table-column prop="articleCnt" label="文章数量" align="center" />
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">{{ scope.row.status == 'Y'?'启用':'禁用' }}</template>
        </el-table-column>
        <el-table-column prop="createTime" label="添加时间" align="center">
          <template slot-scope="scope">{{ dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}</template>
        </el-table-column>
        <el-table-column prop="orderSn" label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="edit(scope.row)">编辑</el-button>
            <el-button type="text" :disabled="scope.row.articleCnt != 0" @click="del(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">

        <el-pagination
          :current-page="page.currentPage"
          :page-sizes="page.pageSizes"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <!-- 新增标签模态框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="50%">
        <el-form ref="formS" :model="formS" size="small" label-width="80px" :rules="rules">
          <el-form-item label="名称" prop="labelName">
            <el-input v-model="formS.labelName" placeholder="请输入名称" type="text" maxlength="10" show-word-limit />
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formS.status">
              <el-radio label="Y">启用</el-radio>
              <el-radio label="N">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button @click="back">取消</el-button>
            <el-button type="primary" @click="preservation">保存</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  labelInfoList,
  labelInfoSort,
  labelInfoAdd,
  labelInfoUpd,
  labelInfoDel
} from '@/api/knowledge'
import Sortable from 'sortablejs'
import dayjs from 'dayjs'
export default {
  data() {
    return {
      // 分页对象
      page: {
        currentPage: 1,
        pageSizes: [10, 15, 20, 25],
        pageSize: 10,
        total: 0
      },
      dayjs,
      dialogFormVisible: false, // 新增作者模态框
      dialogTitle: '',
      form: {
        labelName: '', // 标题关键字
        status: '' // 选择状态
      },
      formS: {
        status: '',
        labelName: ''
      },
      rules: {
        labelName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请上选择状态', trigger: 'change' }
        ]
      },
      tableData: []
    }
  },
  mounted() {
    const { pageType } = this.$route.query
    if (pageType == 'noDataAdd') {
      this.NewLabel()
    }
    this.fetchData()
  },
  methods: {
    // 行拖拽
    rowDrop() {
      // 要侦听拖拽响应的DOM对象
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      const that = this
      Sortable.create(tbody, {
        sort: true,
        animation: 150,
        handle: '.move',
        // 结束拖拽后的回调函数
        onEnd(e) {
          console.log('拖动了行，当前序号：', e)
          const { newIndex, oldIndex } = e
          const currentRow = that.tableData.splice(oldIndex, 1)[0]
          that.tableData.splice(newIndex, 0, currentRow)
          console.log(that.tableData.map(item => item.labelName))
          that.sort()
        }
      })
    },
    // 确定
    preservation() {
      this.$refs['formS'].validate((valid) => {
        if (valid) {
          if (this.formS.id) {
            labelInfoUpd(this.formS).then(res => {
              this.$message.success('操作成功！')
              this.dialogFormVisible = false
              this.fetchData('init')
            })
          } else {
            labelInfoAdd(this.formS).then(res => {
              this.$message.success('操作成功！')
              this.dialogFormVisible = false
              this.fetchData('init')
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    sort() {
      const arr = this.tableData.map((item, index) => {
        return {
          ...item,
          sort: index + 1
        }
      })
      labelInfoSort(arr).then(res => {

      })
    },
    // 返回
    back() {
      this.dialogFormVisible = false
    },
    // 编辑
    edit(data) {
      this.dialogTitle = '修改'
      this.formS = {
        id: data.id,
        labelName: data.labelName,
        status: data.status
      }
      this.dialogFormVisible = true
    },
    // 新增素材
    NewLabel() {
      this.dialogTitle = '新增'
      this.formS = {
        labelName: '',
        status: 'Y'
      }
      this.dialogFormVisible = true
    },
    // 搜索
    fetchData(type) {
      if (type == 'init') {
        this.page.currentPage = 1
      }
      const obj = {
        pageSize: this.page.pageSize,
        currentPage: this.page.currentPage,
        ...this.form
      }
      labelInfoList(obj).then(res => {
        console.log('res', res)
        this.tableData = res.data.list
        this.page.total = res.data.total
        this.$nextTick(() => {
          this.rowDrop()
        })
      })
    },
    // 分页
    handleSizeChange(val) {
      this.page.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.fetchData()
    },
    // 重置
    empty() {
      this.form = this.$options.data().form
    },
    // 删除
    del(data) {
      this.$confirm('此操作将永久删除该标签, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        labelInfoDel({ id: data.id }).then(res => {
          this.$message.success('操作成功！')
          this.fetchData('init')
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped="scoped">
  .head-content {
    width: 100%;

    .head-content-box {
      display: flex;
      align-items: center;

      .head-content-txt {
        font-size: 24px;
        font-weight: 500;
      }

      .head-content-txt-newlyAdded {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-left: 3%;

        .head-content-txt-newlyAdded-icon {
          font-size: 28px;
        }

        .head-content-txt-newlyAdded-txt {
          font-size: 14px;
        }
      }
    }
  }
  .form-content{
    margin-top:10px;
  }
  .move{
    cursor: pointer;
  }
</style>
